#!/usr/bin/python

# Copyright 2011 Portland Transport

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import urllib
from BeautifulSoup import BeautifulStoneSoup
from optparse import OptionParser
import time

p = OptionParser()
p.add_option('-o', '--origin', dest='origin', help='The origin of the trip',
             default='pdx')
p.add_option('-k', '--key', dest='key', help='The TriMet key')
p.add_option('-f', '--file', dest='file', help='The file to read destinations from, one per line')
p.add_option('-d', '--duration', dest='duration', help='The maximum trip duration to consider', type='int')


opts, args = p.parse_args()


# The time for the query
theTime = time.strftime('%I%%3A%M%%20%p').lower()

print 'Testing trips starting from ' + opts.origin + ' at ' + theTime

dests = open(opts.file)

results = []

for dest in dests:
    # get rid of newline
    if dest[-1] == '\n':
        dest = dest[0:-1]

    # build URL
    base  = 'http://developer.trimet.org/ws/V1/trips/tripplanner'
    base += '/fromPlace/%s' % opts.origin
    base += '/toPlace/%s' % dest
    # get it in am/pm not AM/PM
    base += '/time/%s' % theTime
    base += '/arr/D'
    base += '/min/X'
    base += '/appID/%s' % opts.key

    print 'Testing trip to %s... ' % dest

    rawXml = urllib.urlopen(base).read()
    xml = BeautifulStoneSoup(rawXml)

    if len(xml.findAll(name='fromlist')) > 0:
        raise ValueError, 'from location is ambiguous'

    if len(xml.findAll(name='tolist')) > 0:
        print 'Skipping, ambiguous'
        continue

    # loop through result set
    for itin in xml.findAll(name='itinerary'):
        if int(itin.numberoftransfers.string) != 0:
            continue
        if int(itin.duration.string) > opts.duration:
            continue
        print ' - Found reasonable 0-transfer trip using route %s (%s min)' % (itin['viaroute'], itin.duration.string)
        
        results.append(dest)
        break

if len(results) > 0:
    print 'Reachable locations:'
    print ' * ' + '\n * '.join(results) 
else:
    print 'No locations reachable :('
    
